package com.kexun.mvc.resolvers;

import com.kexun.entity.BaseEntity;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.Enumeration;

public class BaseEntityResolver implements BaseResolver {
    @Override
    public boolean supportsParameter(Parameter parameter) {
        try {
            return parameter.getType().newInstance() instanceof BaseEntity;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Object resolveArgument(Parameter parameter, HttpServletRequest req, HttpServletResponse resp) {
        Enumeration<String> parameterNames = req.getParameterNames();
        Object o = null;
        try {
            o = parameter.getType().newInstance();
            while (parameterNames.hasMoreElements()) {
                String s = parameterNames.nextElement();
                String parameter1 = req.getParameter(s);
                BeanUtils.setProperty(o, s, parameter1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }
}
